package user.persistence;


import groupby.util.Pages;
import groupby.util.UtilsTools;

import java.io.File;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import system.model.BasicInfor;
import user.model.BrandInfor;
import user.model.Dynamic;
import user.model.Photoinfor;
import user.model.Pictures;
import user.model.Responses;
import user.model.Topic;
import user.model.UserDetial;
import user.model.Users;

public class UsersDaoImpl extends HibernateDaoSupport implements UsersDao {

	/**
	 * 用户登录
	 */
	public Users usersLogin(final String email,final String password) {
		Users user=(Users)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				 Query query =session.createQuery("from Users user where user.email='"+email.trim()+"' and user.password='"+password.trim()+"'");
				return query.uniqueResult();
			}
			
		});
		return user;
	}

   /**
    * 用户列表
    */
	public List getUserList(final Pages pages,final String email,final String startTime,final String endTime,final int level,final int able) {
	    List userList=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				 String where="";
				if(email!=null&&!email.equals(""))
				{
					where="and user.email like '%"+email+"%'";
				}
				if(startTime!=null&&!startTime.equals(""))
				{
						where+=" and user.registerTime >= '"+startTime+"'";
					
				}
				if(endTime!=null&&!endTime.equals(""))
				{
					
						where+=" and user.registerTime<='"+endTime+"'";
					
				}
				if(level!=-1)
				{
					
						where+=" and user.level='"+level+"'";
					
				}
				if(able!=-1)
				{
					
						where+=" and user.able='"+able+"'";
					
				}
				String hql="from Users user where user.email<>'root' "+where;
				System.out.println(hql);
				int rowCount=getRowCount(hql);
				pages.setRowCount(rowCount);
				pages.setTotalPage(rowCount);
				pages.setPreNextPage();
				Query query =session.createQuery(hql);
				      query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize()); 
				      query.setMaxResults(pages.getPageSize());
				return query .list();
			}
	    	
	    });
		return userList;
	}
	
	public int getRowCount(final String hql)
    {
    	Integer rowCount=0;
    	rowCount=(Integer)this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				return session.createQuery(hql).list().size();
			}
    	});
    	return rowCount;
    }

	/**
	 * 开通申请的用户
	 */
	public boolean ratify(final int id,final  int able) {
		try
		{
			this.getHibernateTemplate().execute(new HibernateCallback(){
	
				public Object doInHibernate(Session session)throws HibernateException, SQLException {
					
					Query query=session.createQuery("update Users user set user.able="+able+" where user.id="+id);
					return query.executeUpdate();
				}
				
			});
			return true;
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 删除用户
	 */
	public boolean deleteUser(int id) {
		final Users user=(Users)this.getHibernateTemplate().get(Users.class, id);
		 this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				session.createQuery("delete from UserDetial detial where detial.userId="+user.getId()).executeUpdate();
				return null;
			}
			 
		 });
		 this.getHibernateTemplate().delete(user);
		
		return true;
	}

	/**
	 * 获得用户信息
	 */
	public UserDetial getSingleUser(final int id) {
		UserDetial userDetial=(UserDetial)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				Query query =session.createQuery("from UserDetial  user where user.userId="+id);
				return query.uniqueResult();
			}
			
		});
		return userDetial;
	}

	/**
	 * 更新用户信息
	 */
	public void updateSingleUser(UserDetial userDetial) {
		this.getHibernateTemplate().update(userDetial);
	}

	/**
	 * checkUserEmail
	 */
	public boolean checkUserEmail(String email) {
		List list=this.getHibernateTemplate().find("from Users u where u.email='"+email+"'");
		if(list!=null&&list.size()==1)
		{
			return true;
		}
		    return false;
	}
   /**
    * 添加用户
    */
	public int addUser(Users user) {
		this.getHibernateTemplate().save(user);
		int id=user.getId();
		return id;
	}
/**
 * 添加用户细节
 */
public boolean addUserDetial(UserDetial userDetial) {
	  try
	  {
		  this.getHibernateTemplate().save(userDetial);
		  return true;
	  }catch(Exception e)
	  {
		  e.printStackTrace();
		  return false;
	  }
}
/**
 *  获得Content
 */
public BasicInfor getBasicInfor(int id) {
	BasicInfor basicInfor =(BasicInfor)this.getHibernateTemplate().get(BasicInfor.class, id);
	return basicInfor;
}
/**
 * update  BasicInfor
 */
public boolean updateBasicInfor(BasicInfor bi) {
	BasicInfor basicInfor =(BasicInfor)this.getHibernateTemplate().get(BasicInfor.class, bi.getId());
	basicInfor.setContent(bi.getContent());
	   this.getHibernateTemplate().update(basicInfor);
	return true;
}

/**
 * 获得我关注的团购
 */
public List attentionGroupbyList(final Integer userId) {
	    List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				String hql="from Groupby g where g.id in(select gc.groupbyId from GroupCriticism gc where gc.userId="+userId+" group by gc.groupbyId order by gc.datetime desc)";
				Query query =session.createQuery(hql);
				query .setFirstResult(0);
				query.setMaxResults(2);
				return query.list();
			}
	    	  
	      });
	return list;
}
/**
 * 修改密码
 */
public boolean modifyUserPassword(Users users) {
	try
	{
	       Users tempUser=(Users)this.getHibernateTemplate().get(Users.class,users.getId());
	       tempUser.setPassword(users.getPassword());
	       this.getHibernateTemplate().update(tempUser);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}

/**
 * 获得我的好友1
 */
public List myFriendList(final Pages pages,final Integer id,final int level) {
	 final UserDetial userDetial=(UserDetial)this.getHibernateTemplate().find("from UserDetial userDetial where userDetial.userId="+id).listIterator().next();
	 if(userDetial.getFriendId()!=null&&!userDetial.getFriendId().equals(""))
	 {
	 List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from Users user , UserDetial userDetial where user.id=userDetial.userId and user.level="+level+" and  userDetial.userId in("+userDetial.getFriendId().substring(0,userDetial.getFriendId().length()-1)+")";
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query =session.createQuery(hql);
		          query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	              query .setMaxResults(pages.getPageSize());
			return query.list();
		}
	   });
	   return list;
	 }else
	 {
		 return null;
	 }
	
 }
/**
 * 添加用户
 */
public boolean addFriend(int userId,int id) {
	UserDetial userDetial=(UserDetial)this.getHibernateTemplate().find("from UserDetial userDetial where userDetial.userId="+userId).iterator().next();
	if(userDetial.getFriendId()==null||userDetial.getFriendId().equals(""))
	{
		userDetial.setFriendId(id+",");
		this.getHibernateTemplate().update(userDetial);
		return true;
	}else 
	{
		String[] ids=userDetial.getFriendId().split(",");
		boolean flag=false;
		for(int i=0;i<ids.length;i++)
		{
			if(ids[i]!=null&&ids[i].equals(id+""))
			{
				flag=true;
				break;
			}
		}
		if(!flag)
		{
			userDetial.setFriendId(userDetial.getFriendId()+id+",");
			this.getHibernateTemplate().update(userDetial);
			return true;
		}
		return false;
	}

}
/**
 * 获得用户
 */
public Users getUsers(int id) {
	Users users=(Users) this.getHibernateTemplate().get(Users.class, id);
	return users;
}
/**
 * 添加动态
 */
public void addDynamic(Dynamic dynamic) {
	dynamic.setUser2(dynamic.getUser2()+",");
	this.getHibernateTemplate().save(dynamic);
}
/**
 * 获得用户的详细信息
 */
public UserDetial getSingleUser(final String userName) {
	UserDetial  userDetial=(UserDetial)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			Query query =session.createQuery(" from UserDetial u where u.website='"+userName+"'");
			return query.uniqueResult();
		}
	});
	return userDetial;
}

/**
 * 获得动态
 */
public List dynamicList(final Pages page,final int id) {
	final UserDetial userDetial=(UserDetial)this.getHibernateTemplate().find("from UserDetial userDetial where userDetial.userId="+id).listIterator().next();
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			Query query =null;
			String[] ids=null;
			if(userDetial.getFriendId()!=null&&!userDetial.getFriendId().equals(""))
			{
				ids=(userDetial.getFriendId()+userDetial.getUserId()).substring(0,userDetial.getFriendId().length()).split(",");
			}else
			{
				ids=new String[1];
				ids[0]=userDetial.getUserId().toString();
			}
				
				String where=" dynamic.user1 like'%>"+id+"%' or";
				for (int i=0;i<ids.length;i++)
				{
					where+=" dynamic.user1 like'%>"+ids[i]+"' or";
				}
				/*for (int i=0;i<ids.length;i++)
				{
					where+=" dynamic.user2 like'%>"+ids[i]+",%' or dynamic.user2 like'%,"+ids[i]+",%' or";
				}*/
				if(!where.equals(""))
				{
					where=where.substring(0,where.length()-2);
				}
				String hql="from Dynamic dynamic where "+where+" order by dynamic.datetime desc";
				int rowCount=getRowCount(hql);
				 page.setRowCount(rowCount);
				 page.setTotalPage(rowCount);
				 page.setPreNextPage();
				 query =session.createQuery(hql);
			     query.setFirstResult((page.getCurrentPage()-1)*page.getPageSize());
		         query .setMaxResults(page.getPageSize()); 
		      return query.list();
		}
	   });
	   return list;
}
/**
 * 获得回应信息
 */
@SuppressWarnings("unchecked")
public List listReplay(final Integer id) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			Query query=session.createQuery(" from Responses r where r.did="+id+" order by r.datetime");
			return query.list();
		}
	});
	return list;
}
/**
 * 添加回应信息
 */
public boolean addReplay(Responses responses) {
	try
	{
	this.getHibernateTemplate().save(responses);
	}catch(Exception e)
	{
		e.printStackTrace();
		return false;
	}
	return true;
}
/**
 * 获得评论信息
 */
public List myCriticism(final Pages pages,final Integer id) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		
		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			String hql="from GroupCriticism  gc where gc.userId="+id+" order by gc.datetime desc";
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
		     query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize()); 
			return query.list();
		}
	});
	return list;
}
/**
 * 添加相册
 */
public boolean addPictures(Pictures picture) {
	try
	{
	this.getHibernateTemplate().save(picture);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 
 * 获得相册列表
 */
public List pictureList(final Pages pages,final String photoName,final String startDate,final String endDate,final Integer id,final String flag,final int category,final String flags) {
	List list =(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from Pictures pic ";
			Query query=null;
			
			if(flag!=null&&!flag.equals(""))
			{
				hql+="where pic.userId="+id;
				 query=session.createQuery(hql);
				
			}else
			{
				if(id!=-1)
				{
					hql+="where pic.userId="+id;
				}else
				{
					hql+="where pic.userId=pic.userId";
				}
				if(photoName!=null&&!photoName.equals(""))
				{
					hql+=" and pic.photoName like'%"+photoName+"%'";
				}
				if(startDate!=null&&!startDate.equals(""))
				{
					hql+=" and pic.datetime>='"+startDate+"'";
				}
				if(endDate!=null&&!endDate.equals(""))
				{
					hql+=" and pic.datetime<='"+endDate+"'";
				}
				
				if(category!=-1)
				{
					hql+=" and pic.categoryId='"+category+"'";
				}
				if(!flags.equals("")&&!flags.equals("-1"))
				{
					hql+=" and pic.recommend='"+flags+"'";
				}
				int rowCount=getRowCount(hql);
				pages.setRowCount(rowCount);
				pages.setTotalPage(rowCount);
				pages.setPreNextPage();
				 query=session.createQuery(hql);
				 query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
		         query .setMaxResults(pages.getPageSize()); 
			
			}
			return query.list();
		}
	});
	return list;
}
/**
 * 删除相册
 */
public boolean delPictures(int picId,String path) {
	Pictures pic=(Pictures)this.getHibernateTemplate().get(Pictures.class, picId);
	try
	{
	this.getHibernateTemplate().delete(pic);
	}catch(Exception e)
	{
		return false;
	}
	path=path+"\\"+pic.getImageFolder();
	path=path.replace("/", File.separator).replace("\\",File.separator);
	File file=new File(path);
	file.delete();
	return true;
}
/**
 * 推荐相册
 */
public boolean ratifyPic(int picId, int able) {
	try
	{
	Pictures pic=(Pictures)this.getHibernateTemplate().get(Pictures.class, picId);
	pic.setRecommend(able);
	this.getHibernateTemplate().update(pic);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 获得单个 相册
 */
public Pictures getPictures(int picId) {
	
	return (Pictures)this.getHibernateTemplate().get(Pictures.class, picId);
}
/**
 * 添加图片
 */
public boolean addPhoto(Photoinfor pi) {
	try
	{
	this.getHibernateTemplate().save(pi);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 显示相册图片
 */
public List showPhotoList(final Pages pages,final  int picId) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			String hql="from Photoinfor p where p.picId="+picId;
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize()); 
			return query.list();
		}
	});
	return list;
}
/**
 * 回应相册信息
 */
public Photoinfor criticismPhoto(final Pages pages,final int photoId,final int picId) {
	Photoinfor photoinfor=(Photoinfor)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from Photoinfor p where p.id="+photoId+" and p.picId="+picId+" order by p.id asc";
			Query query=null;
		    if(picId!=-1)
		    {
		    	hql="from Photoinfor p where p.id="+photoId+" and p.picId="+picId+" order by p.id asc";
		    	query=session.createQuery("from Photoinfor p where p.id<"+photoId+" and p.picId="+picId+" order by p.id desc");
				List prePhotoinfor=(List)query.list();
				if(prePhotoinfor.size()>0)
				{
					pages.setPrePage(((Photoinfor)prePhotoinfor.get(0)).getId());
				}else
				{
					pages.setPrePage(-1);
				}
				query=session.createQuery("from Photoinfor p where p.id>"+photoId+" and p.picId="+picId+" order by p.id asc");
				List nextPhotoinfor=(List)query.list();
				if(nextPhotoinfor.size()>0)
				{
					pages.setNextPage(((Photoinfor)nextPhotoinfor.get(0)).getId());
				}else
				{
					pages.setNextPage(-1);
				}
				query=session.createQuery("from Photoinfor p where  p.picId="+picId+" order by p.id asc");
				List rowNum=(List)query.list();
				pages.setRowCount(rowNum.size());
				for(int i=0;i<rowNum.size();i++)
				{
					if(((Photoinfor)rowNum.get(i)).getId()==photoId)
					{
						pages.setCurrentPage(i+1);
					}
				}
		    }else
		    {
		    	hql="from Photoinfor p where p.id="+photoId+" order by p.id asc";
		    }
			query=session.createQuery(hql);
			return query.uniqueResult();
		}
	});
	return photoinfor;
}
/**
 * 添加品牌信息
 */
public boolean addBrandInfor(BrandInfor brandInfor) {
	try
	{
	this.getHibernateTemplate().save(brandInfor);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 获得品牌信息
 */
public List brandList(final Pages picPages,final  int id) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from BrandInfor b ,Category c where c.id=b.category  and  b.userId="+id+" order by b.datetime desc";
			int rowCount=getRowCount(hql);
			picPages.setRowCount(rowCount);
			picPages.setTotalPage(rowCount);
			picPages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((picPages.getCurrentPage()-1)*picPages.getPageSize());
	         query .setMaxResults(picPages.getPageSize());
			return query.list();
		}	
	});
	return list;
}
/**
 *获得品牌列表
 */
public List brandInforAllList(final Pages pages,final Integer id) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from BrandInfor b ,Category c where c.id=b.category and  b.userId="+id+" order by b.datetime desc";
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize());
			return query.list();
		}
		
	});
	return list;
}
/**
 * 获得单个品牌列表
 */
public List brandSingleCategoryList(final Pages pages, final Integer id,final  int category) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="";
			if(id==-1)
			{
				hql="from BrandInfor b  where b.category="+category+"  order by b.datetime desc";
			}else
			{
				hql="from BrandInfor b  where b.category="+category+" and  b.userId="+id+" order by b.datetime desc";
			}
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize());
			return query.list();
		}
		
	});
	return list;
}
/**
 * 获得单个品牌信息
 */
public BrandInfor singleBrand(int brandId) {
	 
	return (BrandInfor)this.getHibernateTemplate().get(BrandInfor.class, brandId);
}
/**
 * 添加话题
 */
public boolean addTopic(Topic topic) {
	try
	{
	this.getHibernateTemplate().save(topic);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 获得话题列表
 */
public List topicList(final Pages pages,final  Integer id,final String title,final String startDate,final String endDate) {
	List list=(List)this.getHibernateTemplate().executeFind(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from Topic t ,UserDetial ud where ";
			if(id==-1)
			{
				hql+="t.userId=t.userId ";
			}else
			{
				hql+="t.userId="+id+" ";
			}
			if(title!=null&&!title.equals(""))
			{
				hql+=" and t.title like '%"+title+"%'";
			}
			if(startDate!=null&&!startDate.equals(""))
			{
				hql+=" and t.datetime>='"+startDate+"'";
			}
			if(endDate!=null&&!endDate.equals(""))
			{
				hql+=" and t.datetime<='"+endDate+"'";
			}
			if(id==-1)
			{
				hql+=" and t.userId=ud.userId order by t.datetime desc";
			}else
			{
				hql+=" and t.publisher=ud.userId order by t.datetime desc";
			}
			
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize());
			return query.list();
		}
		
	});
	return list;
}
/**
 * 获得单个项目
 */
public Topic getTopic(int topicId) {
	
	return (Topic)this.getHibernateTemplate().get(Topic.class, topicId);
}
/**
 * 更新topicCount
 */
public void updateTopicCount(int topicId) {
	Topic topic=(Topic)this.getHibernateTemplate().get(Topic.class,topicId);
	topic.setReplyCount(topic.getReplyCount()+1);
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	topic.setReplyLastTime(sdf.format(new Date()));
	this.getHibernateTemplate().update(topic);
}
/**
 * 获得其它话题列表
 */
public List topicList(final Pages pages, final int userId, final  int topicId) {
	List list=(List)this.getHibernateTemplate().executeFind(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from Topic t where t.userId="+userId+" and t.id<>"+topicId+" order by t.datetime desc";
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize());
			return query.list();
		}
	});
	return list;
}
/**
 * 获得品牌列表
 */
public List brandInforAllList(final Pages pages,final  Integer id,final  String title,
		final String startDate,final  String endDate,final int categoryId,final String flag) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String where="";
			if(title!=null&&!title.trim().equals(""))
			{
				where=" and b.title like '"+title+"'";
			}
			if(startDate!=null&&!startDate.equals(""))
			{
				
				where+=" and b.startDate>='"+startDate+"'";
				
			}
			if(endDate!=null&&!endDate.equals(""))
			{
				
				where+=" and b.endDate<='"+endDate+"'";
				
			}
			if(categoryId!=-1)
			{
				where+=" and b.category="+categoryId+"";
			}
			if(!flag.equals("-1"))
			{
				where+=" and b.recommendation="+flag;
			}
			String hql="";
			if(id==-1)
			{
				hql="from BrandInfor b ,Category c where c.id=b.category  "+where+" order by b.datetime desc";
			}else
			{
				hql="from BrandInfor b ,Category c where c.id=b.category and  b.userId="+id+" "+where+" order by b.datetime desc";
			}
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize());
			return query.list();
		}
		
	});
	return list;
}
/**
 * 删除图片
 */
public boolean delImage(int brandId, String flag,String image,String path) {
	try
	{
		path=path+"\\"+image;
		path=path.replace("/", File.separator).replace("\\",File.separator);
	File file=new File(path);
	file.delete();
    BrandInfor brand=(BrandInfor)this.getHibernateTemplate().get(BrandInfor.class,brandId);
    if(flag.equals("image1"))
    {
    	brand.setImage1(brand.getImage2());
    	brand.setImage2(brand.getImage3());
    	brand.setImage3(brand.getImage4());
    	brand.setImage4(brand.getImage5());
    	brand.setImage5("");
    }else if(flag.equals("image2"))
    {
    	brand.setImage2(brand.getImage3());
    	brand.setImage3(brand.getImage4());
    	brand.setImage4(brand.getImage5());
    	brand.setImage5("");
    }else if(flag.equals("image3"))
    {
    	brand.setImage3(brand.getImage4());
    	brand.setImage4(brand.getImage5());
    	brand.setImage5("");
    }else if(flag.equals("image4"))
    {
    	
    	brand.setImage4(brand.getImage5());
    	brand.setImage5("");
    }else if(flag.equals("image5"))
    {
    	brand.setImage5("");
    }
    this.getHibernateTemplate().update(brand);
	}catch(Exception e)
	{
		e.printStackTrace();
		return false;
	}
	return true;
}
/**
 * 上传品牌单个图片
 */
public boolean uploadSingleImage(int brandId, String flag, String image) {
	try
	{
	BrandInfor brand=(BrandInfor)this.getHibernateTemplate().get(BrandInfor.class,brandId);
	if(flag.equals("image1"))
    {
    	brand.setImage1(image);
    	
    }else if(flag.equals("image2"))
    {
    	brand.setImage2(image);
    	
    }else if(flag.equals("image3"))
    {
    	brand.setImage3(image);
    }else if(flag.equals("image4"))
    {
    	brand.setImage4(image);
    }else if(flag.equals("image5"))
    {
    	brand.setImage5(image);
    }
	 this.getHibernateTemplate().update(brand);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 更新brand信息
 */
public boolean modifyBrand(int brandId, String title, String content,int category,int category2) {
	try
	{
	BrandInfor brand=(BrandInfor)this.getHibernateTemplate().get(BrandInfor.class,brandId);
		brand.setTitle(title);
		brand.setCategory(category);
		brand.setContent(content);
		brand.setCategory(category);
		brand.setCategory2(category2);
		List imageUrl=UtilsTools.getImgStr(content);
		if(imageUrl!=null&&imageUrl.size()!=0)
		{
			String image=imageUrl.get(0).toString();
			brand.setImage1(image.substring(image.lastIndexOf("/")+1,image.length()));
		}else
		{
			brand.setImage1("img.gif");
		}
	 this.getHibernateTemplate().update(brand);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 推荐品牌
 */
public boolean modifyBrand(int brandId, String flag) {
	try
	{
	BrandInfor brand=(BrandInfor)this.getHibernateTemplate().get(BrandInfor.class,brandId);
	brand.setRecommendation(Integer.parseInt(flag));
	this.getHibernateTemplate().update(brand);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 获得品牌推荐信息
 */
public List brandList(final Pages page,final boolean flag,final String category) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="";
			if(flag)
			{
				hql="from BrandInfor b where  b.recommendation=1  order by b.datetime desc";
			}else
			{
				hql=category+" order by b.datetime desc";
			}
			int rowCount=getRowCount(hql);
			page.setRowCount(rowCount);
			page.setTotalPage(rowCount);
			page.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((page.getCurrentPage()-1)*page.getPageSize());
	         query .setMaxResults(page.getPageSize());
			return query.list();
		}
		
	});
	return list;
}
/**
 * 获得单个类别的所有品牌信息
 */
public List brandSingleCategoryList(final Pages pages,final  Integer id,final String flag) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String hql="from BrandInfor b ,UserDetial ud where b.category="+id+" and b.category2="+flag+" and ud.userId=b.userId and b.recommendation=1 order by b.datetime desc";
			
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query=session.createQuery(hql);
			query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	         query .setMaxResults(pages.getPageSize());
			return query.list();
		}
		
	});
	return list;
}

public List userList(final Pages pages,final  String email,final  String startTime,
		final String endTime,final  String categoryId) {
	 List userList=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				 String where="";
				if(email!=null&&!email.equals(""))
				{
					where="and user.email like '%"+email+"%'";
				}
				if(startTime!=null&&!startTime.equals(""))
				{
						where+=" and user.registerTime >= '"+startTime+"'";
					
				}
				if(endTime!=null&&!endTime.equals(""))
				{
					
						where+=" and user.registerTime<='"+endTime+"'";
					
				}
				
				String hql="from Users user where user.level in("+categoryId+") and user.able=1 "+where;
				
				int rowCount=getRowCount(hql);
				pages.setRowCount(rowCount);
				pages.setTotalPage(rowCount);
				pages.setPreNextPage();
				Query query =session.createQuery(hql);
				      query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize()); 
				      query.setMaxResults(pages.getPageSize());
				return query .list();
			}
	    	
	    });
		return userList;
}
/**
 * 推荐用户
 */
public boolean recommendUser(int userId, int flag) {
	try
	{
	Users user=(Users)this.getHibernateTemplate().get(Users.class,userId);
	user.setRecommend(flag);
	this.getHibernateTemplate().update(user);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 获得推荐用户
 */
public List brandUserList(final Pages page,final  int level,final int flag) {
	 List userList=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				
				
				String hql="from UserDetial ud where ud.userId in (select user.id from Users user where user.level ="+level+" and user.able=1 ";
				if(flag!=-1)
				{
					hql+="and user.recommend="+flag;
				}
				hql+=" ) ";
				int rowCount=getRowCount(hql);
				page.setRowCount(rowCount);
				page.setTotalPage(rowCount);
				page.setPreNextPage();
				Query query =session.createQuery(hql);
				      query.setFirstResult((page.getCurrentPage()-1)*page.getPageSize()); 
				      query.setMaxResults(page.getPageSize());
				return query .list();
			}
	    	
	    });
		return userList;
}

/**
 * 获得品牌用户列表 by category
 */
public List brandUserListMore(final Pages page, final Integer id) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			String hql="from UserDetial ud where ud.categoryId="+id;
			
			int rowCount=getRowCount(hql);
			page.setRowCount(rowCount);
			page.setTotalPage(rowCount);
			page.setPreNextPage();
			Query query =session.createQuery(hql);
			      query.setFirstResult((page.getCurrentPage()-1)*page.getPageSize()); 
			      query.setMaxResults(page.getPageSize());
			return query .list();
		}
		
	});
	return list;
}
/**
 * 查找picture by category 
 */
public List pictureListByCategory(final Pages picPages,final  Integer id) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			String hql="from Pictures pic where pic.recommend=1 and pic.categoryId="+id;
			
			int rowCount=getRowCount(hql);
			picPages.setRowCount(rowCount);
			picPages.setTotalPage(rowCount);
			picPages.setPreNextPage();
			Query query =session.createQuery(hql);
			      query.setFirstResult((picPages.getCurrentPage()-1)*picPages.getPageSize()); 
			      query.setMaxResults(picPages.getPageSize());
			return query .list();
		}
		
	});
	return list;
}
/**
 * 修改相册图片信息
 */
public boolean photoModify(Photoinfor photoinfor) {
	try
	{
	this.getHibernateTemplate().update(photoinfor);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 删除相册里的图片
 */
public boolean photoDel(int photoId,String path) {
	try
	{
		Photoinfor p=(Photoinfor)this.getHibernateTemplate().get(Photoinfor.class, photoId);
		Pictures pic=(Pictures)this.getHibernateTemplate().get(Pictures.class, p.getPicId());
		path=path+"/"+p.getPhotoName();
		path=path.replace("/", File.separator).replace("\\",File.separator);
		File file=new File(path);
		file.delete();
		if(p.getPhotoName().equals(pic.getFace()))
		{
			pic.setFace("");
			this.getHibernateTemplate().update(pic);
		}
	    this.getHibernateTemplate().delete(p);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 设图片为相册图片
 */
public boolean pictureFace(int picId, String image) {
	try
	{
		Pictures pic=(Pictures)this.getHibernateTemplate().get(Pictures.class,picId);
		pic.setFace(image);
	    this.getHibernateTemplate().update(pic);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 关注我的人
 */
@SuppressWarnings("unchecked")
public List friendToMeList(final Pages pages,final int userId) {
	final List idsList=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			Query query=session.createSQLQuery("select  SUBSTRING_INDEX(dynamic.user1,'>',-1) as ids from dynamic dynamic where dynamic.user2 like '%>"+userId+",' group by ids");
			
			return query.list();
		}
	});
	
	
	if(idsList.size()!=0)
	{
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			String ids="";
			for (int i=0;i<idsList.size();i++)
			{
				ids+=idsList.get(i)+",";
			}
			ids=ids.substring(0,ids.length()-1);
			String hql="from Users user , UserDetial userDetial where user.id=userDetial.userId and  userDetial.userId in("+ids+")";
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query =session.createQuery(hql);
		          query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize());
	              query .setMaxResults(pages.getPageSize());
			return query.list();
		}
	   });
	  return list;
	}
	  return null;
	 
}
/**
 * 删除品牌
 */
public boolean delBrand(int brandId, String path) {
	try
	{
	path=path.replace("/", File.separator).replace("\\",File.separator);
	
	BrandInfor brand=(BrandInfor)this.getHibernateTemplate().get(BrandInfor.class, brandId);
	if(brand.getImage1()!=null&&!brand.getImage1().equals(""))
	{
		File file=new File(path);
		file.delete();
	}
	if(brand.getImage2()!=null&&!brand.getImage2().equals(""))
	{
		File file=new File(path);
		file.delete();
	}
	if(brand.getImage3()!=null&&!brand.getImage3().equals(""))
	{
		File file=new File(path);
		file.delete();
	}
	if(brand.getImage4()!=null&&!brand.getImage4().equals(""))
	{
		File file=new File(path);
		file.delete();
	}
	this.getHibernateTemplate().delete(brand);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 *删除话题
 */
public boolean delTopic(int topicId) {
	try
	{
	final Topic topic=(Topic)this.getHibernateTemplate().get(Topic.class, topicId);
	this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			Query query =session.createQuery("delete GroupCriticism gc where gc.groupbyId="+topic.getId());
			query.executeUpdate();
			return null;
		}
		
	});
	this.getHibernateTemplate().delete(topic);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 更新话题
 */
public boolean modifyTopic(Topic topicInfor) {
	try
	{
	  this.getHibernateTemplate().update(topicInfor);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 修改邮箱
 */
public boolean modifyEmail(Users users) {
	try
	{
	  this.getHibernateTemplate().update(users);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 修改相册
 */
public boolean modifyPicture(Pictures pic) {
	try
	{
	  this.getHibernateTemplate().update(pic);
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 找回密码
 */
public Users findUserPassword(String email) {
	
	return (Users)this.getHibernateTemplate().find("from Users users where users.email='"+email+"'").get(0);
}
/**
 * 删除用户所有信息
 */
public boolean findUserPassword(final Integer id) {
   try
   {
	   this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			Query query =session.createQuery("delete from BrandInfor bi where bi.userId="+id);
			      query.executeUpdate();
			      query =session.createQuery("delete from GroupCriticism  gc where gc.userId="+id);
			      query.executeUpdate();
			      query =session.createQuery("delete from Photoinfor pi where pi.picId in(select pi.id from Pictures  pi where pi.userId="+id+")");
			      query.executeUpdate();
			      query =session.createQuery("delete from Pictures  p where p.userId="+id);
			      query.executeUpdate();
			      query =session.createQuery("delete from Responses  r where r.userInfor like('%,"+id+",%'");
			      query.executeUpdate();
			      query =session.createQuery("delete from Topic  t where t.userId="+id);
			      query.executeUpdate();
			      query =session.createQuery("delete from Dynamic  d where d.user1 like '%<>"+id+"%'");
			      query.executeUpdate();
			return null;
		}
		   
	   });
   }catch(Exception e)
   {
	   return false;
   }
   
   return true;
}
/**
 * 置顶
 */
public boolean top(final int brandId, final String flag) {
	try
	{
		this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				Query query=session.createQuery("update BrandInfor br set br.top="+flag+" where br.id="+brandId);
				return query.executeUpdate();
			}
		});
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 获得列表
 */
public List menageCulmn(final Pages pages,final  String title,final  String startTime,
		String endTime) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			String hql="";
			   if(title!=null&&!title.equals(""))
			   {
				   hql+=" si.category like '%"+title+"%' ";
			   }
			 if(!hql.equals(""))
			 {
				 hql="from BasicInfor si where "+hql;
			 }else
			 {
				 hql="from BasicInfor si  ";
			 }
			int rowCount=getRowCount(hql);
			pages.setRowCount(rowCount);
			pages.setTotalPage(rowCount);
			pages.setPreNextPage();
			Query query =session.createQuery(hql);
			      query.setFirstResult((pages.getCurrentPage()-1)*pages.getPageSize()); 
			      query.setMaxResults(pages.getPageSize());
			return query .list();
		}
		
	});
	return list;
}
/**
 * 删除栏目
 */
public boolean delculmn(final int id) {
    try
    {
    	this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
			Query query=session.createQuery("delete from BasicInfor  bi where bi.id="+id);
				return query.executeUpdate();
			}
    	});
    }catch(Exception e)
    {
    	return false;
    }
    return true;
}
/**
 * 添加栏目
 */
public boolean addculmn(String title) {
	try
	{
	BasicInfor  bi=new BasicInfor();
	bi.setCategory(title);
	this.getHibernateTemplate().save(bi);
	}catch(Exception e)
	{
		e.printStackTrace();
		return false;
	}
	return true;
}
/**
 * 栏目列表
 */
public List culmnlist() {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			
			Query query=session.createQuery("from BasicInfor ");
			return query.list();
		}
		
	});
	return list;
}
/**
 * 获得分类用户
 */
public List findCategoryUserList() {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,SQLException {
			Query query=session.createQuery("from UserDetial userd where userd.userId in(select user.id from Users user where user.level=4)");
			return query.list();
		}
		
	});
	return list;
}
/**
 * 删除品牌所有
 */
public boolean delAllTopicForUser(final int brandId) {
	try
	{
	  this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws HibernateException,SQLException {
				Query query=session.createQuery("delete from Topic topic where topic.userId="+brandId);
				return query.executeUpdate();
			}
	    	
	    });
	}catch(Exception e)
	{
		return false;
	}
	return true;
}
/**
 * 获得关注我的人的列表
 */
public int meToFriendList(int userId) {
	String hql="from Users user,UserDetial userDetial where user.level=2 and user.id=userDetial.userId and userDetial.friendId like '%"+userId+",%'";
	int rowCount=getRowCount(hql);
	return rowCount;
}
/**
 * 关注我的人
 */
public List friendToMe(final Pages page,final int userId) {
	List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			String hql="from Users user,UserDetial userDetial where user.level=2 and user.id=userDetial.userId and userDetial.friendId like '%"+userId+",%'";
			int rowCount=getRowCount(hql);
			page.setRowCount(rowCount);
			page.setTotalPage(rowCount);
			page.setPreNextPage();
			Query query =session.createQuery(hql);
			      query.setFirstResult((page.getCurrentPage()-1)*page.getPageSize()); 
			      query.setMaxResults(page.getPageSize());
			return query .list();
		}
		
	});
	return list;
}

}
